<template>
  <div class="nav-menu">
    <div class="logo">
      <img class="img" src="~@/assets/img/logo.svg" alt="logo" />
      <p v-if="!isCollapse" class="obj-word">Vue3+TS</p>
    </div>
    <el-menu
      background-color="#001529"
      text-color="#fff"
      class="el-menu-vertical-demo"
      :collapse="isCollapse"
      :default-active="defaultValue"
      unique-opened
    >
      <template v-for="(item, index) in userMenus" :key="item.id">
        <template v-if="item.type === 1">
          <el-sub-menu :index="index + ''">
            <template #title>
              <span>{{ item.name }}</span>
            </template>
            <template v-for="subitem in item.children" :key="subitem.key">
              <el-menu-item
                :index="subitem.id + '|'"
                @click="handleMenuItemClick(subitem.url)"
                >{{ subitem.name }}</el-menu-item
              >
            </template>
          </el-sub-menu>
        </template>
        <template v-else-if="item.type === 2">
          <el-menu-item>{{ item.name }}</el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from "vue";
import { useStore } from "@/store";
import { useRouter, useRoute } from "vue-router";
import { pathMapToMenu } from "@/utils/map-menus";

export default defineComponent({
  props: {
    isCollapse: {
      type: Boolean,
      default: false,
    },
  },
  components: {},
  setup() {
    const store = useStore();
    const userMenus = computed(() => store.state.loginModule.userMenus);

    const router = useRouter();
    const handleMenuItemClick = (url: string) => {
      router.push({
        path: url ?? "/not-found",
      });
    };

    // 获取当前路由对象
    const route = useRoute();
    // 得到当前路由路径
    const currentPath = route.path;
    // 获取当前路由路径对应的 后端返回的菜单对象
    const menu = pathMapToMenu(userMenus.value, currentPath);
    // 设置与上面for循环时index一样的值。
    const defaultValue = ref(menu.id + "|");
    return {
      userMenus,
      handleMenuItemClick,
      defaultValue,
    };
  },
});
</script>

<style scoped lang="less">
.nav-menu {
  height: 100%;
  background-color: #001529;
  .logo {
    display: flex;
    height: 28px;
    padding: 12px 10px 8px 10px;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    .img {
      height: 100%;
      margin: 0 10px;
    }
    .obj-word {
      // box-sizing: border-box;
      // height: 100%;
      line-height: 100%;
      color: white;
    }
  }
  .el-menu {
    border-right: none;
  }
}
</style>
